<template>
  <el-dialog v-model="visible" title="PDF PREVIEW" width="80%" @close="closeDialog">
    <div class="pdf-container">
      <pdf v-if="pdfUrl" :src="pdfUrl" :httpHeaders="{ 'content-disposition': 'inline' }" />

      <!-- <iframe v-if="pdfUrl" :src="pdfUrl" width="100%" height="600px"></iframe> -->

      <div v-loading="loading" v-else></div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button>DELETE PDF</el-button> -->
        <el-icon @click="handleDownloadPdf" style="font-size: 30px;font-weight: bold;"><Download /></el-icon>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, watch } from "vue";

export default {
  // components: { Pdf },
  props: {
    pdfUrl: {
      type: String,
      required: true
    },
    pdfName: {
      type: String,
      required: true
    },
    modelValue: {
      type: Boolean,
      required: true
    }
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const loading = ref(true);
    const visible = ref(false);

    watch(
      () => props.modelValue,
      newVal => {
        visible.value = newVal;
      }
    );


    // if (newVal && props.pdfUrl) {
    //       fetchPdf(props.pdfUrl);
    //     }
    //   }
    // );

    // const fetchPdf = async (url) => {
    //   try {
    //     const response = await fetch(url, { mode: "cors" });
    //     const blob = await response.blob();
    //     pdfBlobUrl.value = URL.createObjectURL(blob);
    //   } catch (error) {
    //     console.error("PDF 加载失败:", error);
    //   }
    // };

    const closeDialog = () => {
      emit("update:modelValue", false);
    };

    const handleDownloadPdf = () => {
      downloadPdf();
    };

    const downloadPdf = async () => {
      const pdfUrl = props.pdfUrl;
      try {
        const response = await fetch(pdfUrl, { mode: "no-cors" }); //, { mode: "no-cors" }
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = props.pdfName;
        link.click();
        window.URL.revokeObjectURL(url); // 释放 URL
      } catch (error) {
        console.error("下载失败:", error);
      }
    };

    return { loading, visible, closeDialog, handleDownloadPdf };
  }
};
</script>

<style scoped>
.pdf-container {
  /* display: flex;
  justify-content: center;
  align-items: center;
   */
  /* max-height: 70vh;
  overflow: auto; */
}
</style>
